  <?php
   # This premargin stuff is my attempt at sanely formatting the HTML output without shooting my CPU usage through the roof.
   $pmc = 2;
   $pm[0] = "";
   $pm[1] = " ";
   $pm[2] = "  ";
   $pm[3] = "   ";
   $pm[4] = "    ";
   $pm[5] = "     ";
   $pm[6] = "      ";
   $pm[7] = "       ";
   $pm[8] = "        ";
   $pm[9] = "         ";
   $pm[10] = "          ";

   $cd_sizes[0]['name'] = "Fine";
   $cd_sizes[1]['name'] = "Diminutive";
   $cd_sizes[2]['name'] = "Tiny";
   $cd_sizes[3]['name'] = "Small";
   $cd_sizes[4]['name'] = "Medium";
   $cd_sizes[5]['name'] = "Large";
   $cd_sizes[6]['name'] = "Huge";
   $cd_sizes[7]['name'] = "Gargantuan";
   $cd_sizes[8]['name'] = "Colossal";
   $cd_sizes['lower'] = 0;
   $cd_sizes['upper'] = 8;

   $cs_sizes[0]['modifier'] = 8;
   $cs_sizes[1]['modifier'] = 4;
   $cs_sizes[2]['modifier'] = 2;
   $cs_sizes[3]['modifier'] = 1;
   $cs_sizes[4]['modifier'] = 0;
   $cs_sizes[5]['modifier'] = -1;
   $cs_sizes[6]['modifier'] = -2;
   $cs_sizes[7]['modifier'] = -4;
   $cs_sizes[8]['modifier'] = -8;

   #$hidden_by_default[toc] = true;
   #$hidden_by_default[cd] = true;
   #$hidden_by_default[abilities] = true;
   #$hidden_by_default[cs_hp] = true;
   #$hidden_by_default[cs_ac] = true;
   #$hidden_by_default[cs_initiative] = true;
   #$hidden_by_default[cs_other] = true;
   $hidden_by_default[saves] = true;
   $hidden_by_default[ab] = true;
   $hidden_by_default[weapons] = true;
   $hidden_by_default[skills] = true;
   $hidden_by_default[gear] = true;
   $hidden_by_default[money] = true;
   $hidden_by_default[feats] = true;
   $hidden_by_default[weight] = true;
   $hidden_by_default[languages] = true;
   $hidden_by_default[spells] = true;

   $pebug_depth = 0;
   $pebug_history[0] = "Body";

   $no_showhide[top] = 1;

   function pebug_set($func) {
    global $pebug_depth;
    global $pebug_history;

    $pebug_history[++$pebug_depth] = $func;
   }

   function pebug_restore(){
    global $pebug_depth;
    $pebug_depth--;
   }
  
   function escapeit ($input ) {
    $intermediate = str_replace( '"', "&#34;", $input);
    $intermediate = str_replace( "'", "&#39;", $intermediate);
    if (get_magic_quotes_gpc()) {
      $intermediate = stripslashes( $intermediate);
    }
    $result = $intermediate;
    return $result;
   }

   function hidden ($class){
    pebug_set("hidden");
    # This function checks to see if something is supposed to be hidden.
    # There are three ways to know.  These first two take precedence:
    # - Was the hide button pressed?  / either /    \
    # - Was the show button pressed?  \       /  or /
    # The third and fourth ways may be overridden:
    # - Was the hide button pressed previously?
    # - What is the default setting?

    # hideme -- return value.
    # false = show
    # true = hide

    global $hidden_by_default;

    pebug("hidden_by_default[$class]: " . $hidden_by_default[$class]);

    if (get_var("hide$class")) {
     # hide button was pressed.
     store_flag("hidden$class");
     $hideme = true;
    } elseif (get_var("show$class")) {
     # Show button was pressed.
     $hideme = false;
    } elseif (get_var("hidden$class")) {
     # Hide button was previously pressed, and section should remain hidden.
     store_flag("hidden$class");
     $hideme = true;
    } elseif ($hidden_by_default[$class]) {
     $hideme = true;
    } else {
     $hideme = false;
    }

    pebug_restore();
    return $hideme;
   }

   function newdiv ($class) {
    global $pm;
    global $pmc;

    pebug_set('newdiv');

    pebug("Opening div: $class");

    if (hidden($class)) {
     pebug("newdiv: Hiding $class");
     print "\n" . $pm[$pmc++] . "<div style=\"display: none;\">\n";
    } else {
     print "\n" . $pm[$pmc++] . "<div class=\"$class\">\n";
    }

    pebug_restore();
   }

   function enddiv() {
    global $pm;
    global $pmc;

    pebug_set('enddiv');

    print "\n" . $pm[--$pmc] . "</div>\n";
    pebug('Closing div');

    pebug_restore();
   }

   function gprint($data) {
    # Do NOT call pebug from here. pebug calls this function!
    global $pm;
    global $pmc;
    print "\n" . $pm[$pmc] . $data . "\n";
   }

   function hprint($level, $anchor, $title) {
    global $no_showhide;
    pebug_set("hprint");
    pebug("$anchor");

    if (hidden($anchor)) {
     $bname="show$anchor";
     $bvalue="Show";
    } else {
     $bname="hide$anchor";
     $bvalue="Hide";
     if($anchor != 'cs') {
      $badditional = "<input type=\"submit\" value=\"Update\"><input type=\"reset\" value=\"Undo\"><input type=\"submit\" name=\"debug\" value=\"Debug\">";
     }
    }

    $buttoncode="<input type=\"submit\" name=\"$bname\" value=\"$bvalue\"/>" . $badditional;

    if($no_showhide[$anchor]) {
     gprint("<a name=\"$anchor\"><span class=\"heading$level\">$title</span></a><br/>");
    } else {
     gprint("<a name=\"$anchor\"><span class=\"heading$level\">$title ($buttoncode)</span></a><br/>");
    }

    pebug_restore();
   }

   function psubmit($label, $name) {
    gprint ("<input type=\"submit\" name=\"$name\" value=\"$label\"/>");
   }

   function ptext($label, $name) {
    gprint ("<span class=\"ptext\">$label:</span> <input type=\"text\" name=\"$name\"/><br/>");
   }

   function ptextarea($label, $name) {
    gprint ("<span class=\"ptext\">$label:</span> <input type=\"textarea\" name=\"$name\"/><br/>");
   }

   # No, not as in d20 standard actions.  This function includes those values we want scattered throughout the page for easy access.
   function pstdaction() {
    newdiv("stdaction_outer");
    newdiv("stdaction_inner");
    gprint("<input type=\"submit\" value=\"Update\"><input type=\"reset\" value=\"Undo\"><input type=\"submit\" name=\"debug\" value=\"Debug\">");
    enddiv();
    enddiv();
   }

   function printfloater() {
    newdiv("stdfloat");
    gprint("<input type=\"submit\" value=\"Update\"><input type=\"reset\" value=\"Undo\"><input type=\"submit\" name=\"debug\" value=\"Debug\">");
    enddiv();
   }
    
   function ptrack ($label, $varname) {
    if (get_var($varname) or get_var("show_$varname")) {
     gprint ("<span class=\"field_label\">$label:</span> <input type=\"text\" name=\"$varname\" value=\"" . get_var($varname) . "\"><br/>\n");
    } else {
     gprint ("<span class=\"field_label\">$label:</span> ");
     psubmit("Create value", "show_$varname");
     gprint ("<br>");
     gprint ("<br>");
    }
   }

   function print_field($class, $name, $value) {
    global $pm;
    global $pmc;
    print $pm[$pmc] . "<span class=\"$class\">$name:</span> <span class=\"$class" . "_value\">$value</span><br/>\n";
   }
   
   function print_inline_field($class, $name, $value) {
    print "<span class=\"$class\">$name:</span> <span class=\"$class" . "_value\">$value</span>";
   }

   function store_var($varname, $value) {
    global $pm;
    global $pmc;

    pebug_set('store_var');
    if (!($value)) {
     pebug("BREVITY ERROR: Attempt to store empty variable to $varname.");
    } elseif ($value == "0") {
     # Do not remove quotes around 0 on above line; doing so will return true for all string values.
     pebug("BREVITY ERROR: Storing 0 value to $varname.");
    }

    gprint("<input type=\"hidden\" name=\"$varname\" value=\"$value\">");
    pebug("Saved $varname, $value");

    pebug_restore();
   }

   function store_numvar($varname, $value) {
    # For URL brevity's sake, if $value is zero, or empty, we won't store it.
    pebug_set('store_numvar');
    if (($value != 0) and ($value != null)) {
     store_var($varname, $value);
    } else {
     pebug("Not storing $value in $varname");
    }
    pebug_restore();
   }

   function store_flag($flagname) {
    store_var($flagname, 1);
   }

   # Yeah, I know it seems redundant.  But what if I wanted to switch from the GET method to the POST method? Or to some other way of saving state?
   function get_var($varname) {
    pebug_set('get_var');
    $result = escapeit($_GET[$varname]);
    pebug("Got $varname: $result");

    pebug_restore();
    return $result;
   }

   function pebug($text) {
    # DO NOT Call get_var from this function.  You'll enter into an infinite loop!
    global $pebug_history;
    global $pebug_depth;
    $debugstatus = $_GET['debug'];
    #$debugstatus = true;
    if($debugstatus) {
     print "\n<span class=\"debug\">" . $pebug_history[$pebug_depth] . ": $text</span><br/>\n";
    }
    
   }

   function abilitygen ($ability) {
    #Prepare the data we'll need for output.
    # "asm" is the prefix used for variables specific to Ability Score Modifiers.
    # "amm" is the prefix used for variables specific to Ability Modifier Modifiers. (Sorry!)
    $ability_variable = "abililty_" . $ability;

    # Ability Score Modifier variables    
    $asm_count = get_var("asm_count_$ability");
    $addasm="addasm$ability";
    $addasmvalue="newasmvalue$ability";
    $addasmsource="newasmsource$ability";
    $asm_count = get_var("asm_count_$ability");
    $asm_index_offset = 0;

    # Ability Modifier Modifier variables
    $amm_count = get_var("amm_count_$ability");
    $addamm="addamm$ability";
    $addammvalue="newammvalue$ability";
    $addammsource="newammsource$ability";
    $amm_index_offset = 0;

    # Iterate through all the known modifiers.
    for ($asm_index=1; $asm_index <= $asm_count; $asm_index++):
     $asm_index_modified= $asm_index + $asm_index_offset;
     $asm_original_id = "asm_$ability$asm_index";
     $asm_new_id = "asm_$ability$asm_index_modified";
     $asmvaluevar = "asm_value_$asm_original_id";
     $asmsourcevar = "asm_source_$asm_original_id";
     $asmvalue = get_var($asmvaluevar);
     $asmsource = get_var($asmsourcevar);
     $removeasm = "remove_$asm_original_id";

     # Weed out any selected for removal.
     if (get_var($removeasm)) {
      $asm_index_offset--;
     } else {
      $asmvaluevar = "asm_value_$asm_new_id";
      $asmsourcevar = "asm_source_$asm_new_id";
      $removeasm = "remove_$asm_new_id";
      
      # Store any retained in the asm array.
      $ASM["removeasm$asm_new_id"] = $removeasm;
      $ASM["asmvaluevar$asm_new_id"] = $asmvaluevar;
      $ASM["asmvalue$asm_new_id"] = $asmvalue;
      $ASM["asmsourcevar$asm_new_id"] = $asmsourcevar;
      $ASM["asmsource$asm_new_id"] = $asmsource;
     }
    endfor;

    #If they filled in the field to add a new modifier...
    if (get_var($addasmvalue)) {
     $asm_index_modified= $asm_index + $asm_index_offset;
     $asm_id = "asm_$ability$asm_index_modified";
     $asmvaluevar = "asm_value_$asm_id";
     $asmsourcevar = "asm_source_$asm_id";
     $asmvalue = get_var($addasmvalue);
     $asmsource = get_var($addasmsource);
     $removeasm = "remove_$asm_id";
     
     $ASM["removeasm$asm_id"] = $removeasm;
     $ASM["asmvaluevar$asm_id"] = $asmvaluevar;
     $ASM["asmvalue$asm_id"] = $asmvalue;
     $ASM["asmsourcevar$asm_id"] = $asmsourcevar;
     $ASM["asmsource$asm_id"] = $asmsource;
     
     # We now have one more modifier.
     $asm_count++;
    }
    $asm_count += $asm_index_offset;
    

    # Iterate through all the known modifiers.
    for ($amm_index=1; $amm_index <= $amm_count; $amm_index++):
     $amm_index_modified= $amm_index + $amm_index_offset;
     $amm_original_id = "amm_$ability$amm_index";
     $amm_new_id = "amm_$ability$amm_index_modified";
     $ammvaluevar = "amm_value_$amm_original_id";
     $ammsourcevar = "amm_source_$amm_original_id";
     $ammvalue = get_var($ammvaluevar);
     $ammsource = get_var($ammsourcevar);
     $removeamm = "remove_$amm_original_id";

     # Weed out any selected for removal.
     if (get_var($removeamm)) {
      $amm_index_offset--;
     } else {
      $ammvaluevar = "amm_value_$amm_new_id";
      $ammsourcevar = "amm_source_$amm_new_id";
      $removeamm = "remove_$amm_new_id";
      
      # Store any retained in the amm array.
      $AMM["removeamm$amm_new_id"] = $removeamm;
      $AMM["ammvaluevar$amm_new_id"] = $ammvaluevar;
      $AMM["ammvalue$amm_new_id"] = $ammvalue;
      $AMM["ammsourcevar$amm_new_id"] = $ammsourcevar;
      $AMM["ammsource$amm_new_id"] = $ammsource;
     }
    endfor;

    #If they filled in the field to add a new modifier...
    if (get_var($addammvalue)) {
     $amm_index_modified= $amm_index + $amm_index_offset;
     $amm_id = "amm_$ability$amm_index_modified";
     $ammvaluevar = "amm_value_$amm_id";
     $ammsourcevar = "amm_source_$amm_id";
     $ammvalue = get_var($addammvalue);
     $ammsource = get_var($addammsource);
     $removeamm = "remove_$amm_id";
     
     $AMM["removeamm$amm_id"] = $removeamm;
     $AMM["ammvaluevar$amm_id"] = $ammvaluevar;
     $AMM["ammvalue$amm_id"] = $ammvalue;
     $AMM["ammsourcevar$amm_id"] = $ammsourcevar;
     $AMM["ammsource$amm_id"] = $ammsource;
     
     # We now have one more modifier.
     $amm_count++;
    }
    $amm_count += $amm_index_offset;
    
    # Calculate Effective ability score and Effective Ability Modifier
    if (get_var($ability_variable)) {
 
     #Calculate effective ability score
     $ability_effective_score = get_var($ability_variable);
     for ($asm_index=1; $asm_index <= $asm_count; $asm_index++):
      $asm_id = "asm_$ability$asm_index";
      $asmvalue = $ASM["asmvalue$asm_id"];
      $ability_effective_score += $asmvalue;
     endfor;
 
     #Calculate ability modifier
     # d20's ability modifiers center on 10 as a zero point, and increase one point for every two points of ability score, rounding down.

     if ($ability_effective_score > 10 ) {
      $ability_modifier = round(($ability_effective_score - 10) / 2);
     } else {
      $ability_modifier = round(($ability_effective_score - 10) / 2 - 0.5);
     }

     $effective_ability_modifier = $ability_modifier;

     # Add AMMs

     for ($amm_index=1; $amm_index <= $amm_count; $amm_index++):
      $amm_id = "amm_$ability$amm_index";
      $ammvalue = $AMM["ammvalue$amm_id"];
      $effective_ability_modifier += $ammvalue;
     endfor;
    }
    # Time for output!
    
    newdiv("ability_block");
    gprint ("<span class=\"ability_title\">$ability</span><br/>");
    #pstdaction();


    ptrack ("Base Score", $ability_variable);
    
    # If they haven't entered an ability value yet, we don't want to look like idiots showing calculations based on it.
    if (get_var($ability_variable)) {
     print_inline_field("calculated_field", "Effective Ability Score", $ability_effective_score);
     gprint ("<span class=\"calculation_source\">(" . get_var($ability_variable) . ")");
     $asm_index = 1;
     for (; $asm_index <= $asm_count; $asm_index++):
      $asm_id = "asm_$ability$asm_index";
      $removeasm = $ASM["removeasm$asm_id"];
      $asmvalue = $ASM["asmvalue$asm_id"];
      $asmsource = $ASM["asmsource$asm_id"];
      $asmvaluevar = $ASM["asmvaluevar$asm_id"];
      $asmsourcevar = $ASM["asmsourcevar$asm_id"];

      print "+ <input type=\"submit\" name=\"$removeasm\" value=\"$asmvalue ($asmsource)\">";
      store_var($asmvaluevar, $asmvalue);
      store_var($asmsourcevar, $asmsource);
      
     endfor;
     print "</span><br/>";

     print_inline_field("calculated_field", "Ability Modifier", $effective_ability_modifier);
     gprint ("<span class=\"calculation_source\">(" . $ability_modifier . ")");
     $amm_index = 1;
     for (; $amm_index <= $amm_count; $amm_index++):
      $amm_id = "amm_$ability$amm_index";
      $removeamm = $AMM["removeamm$amm_id"];
      $ammvalue = $AMM["ammvalue$amm_id"];
      $ammsource = $AMM["ammsource$amm_id"];
      $ammvaluevar = $AMM["ammvaluevar$amm_id"];
      $ammsourcevar = $AMM["ammsourcevar$amm_id"];

      print "+ <input type=\"submit\" name=\"$removeamm\" value=\"$ammvalue ($ammsource)\">";
      store_var($ammvaluevar, $ammvalue);
      store_var($ammsourcevar, $ammsource);
      
     endfor;
     print "</span><br/>";
    }

    psubmit("Add Ability Modifier", $addasm);
    psubmit("Add Ability Bonus Modifier", $addamm);

    # We only want the "Add modifier" box visible if the customer has chosen to add a modifier.

    if (get_var("$addasm")) {

     newdiv("ability_addasm_outer");
     newdiv("ability_addasm_inner");
     gprint("<p>New <em>Ability Score</em> Modifier: <input class=\"asm_input\" type=\"text\" name=\"$addasmvalue\"><br/>\n");
     gprint("Source of New <em>Ability Score</em> Modifier: <input class=\"asm_input\" type=\"text\" name=\"$addasmsource\"></span><br/>\n");
     gprint("<input type=\"submit\" value=\"Add Modifier\"></p>\n");
     enddiv();
     enddiv();
    }

    if (get_var("$addamm")) {

     newdiv("ability_addamm_outer");
     newdiv("ability_addamm_inner");
     gprint("<p>New <em>Ability Modifier</em> Modifier: <input type=\"text\" name=\"$addammvalue\"><br/>\n");
     gprint("Source of New <em>Ability Bonus</em> Modifier: <input type=\"text\" name=\"$addammsource\"><br/>\n");
     gprint("<input type=\"submit\" value=\"Add Modifier\"></p>");
    
 
     enddiv();
     enddiv();
    }

    enddiv(); // Hide ability block
    # Save out modifier counts
    store_numvar("asm_count_$ability", $asm_count);
    store_numvar("amm_count_$ability", $amm_count);
   }
  ?>
<html>
 <head>
  <?php
   $cd_name = get_var("cd_name");
   if (get_var("cd_name")) {
    gprint("<title>$cd_name's Character Sheet</title>\n");
   } else {
    gprint("<title>Blank d20 Character Sheet</title>\n");
   }
  ?>
  <link rel="stylesheet" href="charsheet.css" type="text/css">
 </head>
 <body>
  <form>
   <?php

   printfloater();

    $cd_name = get_var("cd_name");
    if (get_var("cd_name")) {
     hprint(1, "top", "$cd_name's Character Sheet");
    } else {
     hprint(1, "top", "Blank d20 Character Sheet");
    }
    newdiv("top");
   ?>
   <p>To use this character sheet, simply fill in any necessary values.  To save your character sheet for later editing, bookmark this page, or save the currently displayed address somewhere.  You may want to click the <? psubmit("Update", 'update') ?> button twice, to ensure you have the shortest URL possible.  The <input type="reset" value="Undo"> button removes any change you haven't yet submitted.  The <? psubmit("Hide", 'generic_hide') ?> button hides a section of the page so you don't have to see it or scroll past it.  The <? psubmit("Show", 'generic_show') ?> button makes a section of the page visible again.</p>
   <p>Finally, you can click the <? psubmit("Debug", 'debug') ?> button if you want, but it merely acts like the Update button, with the dubious benefit of showing you a great deal of debugging information.</p>
   <p>This is <em>not</em> a character generator.  For that, check out any of the fine programs out there, such as the Open-Source PCGen, or WOTC's own (what'sitcalled?).  This software is intended to simplify tracking stats and making rolls.</p>
   <?php
    hprint(3, "toc", "Table of Contents");
    newdiv("toc");
   ?>
    <ul>
     <li><a href="#top">Top</a></li>
     <ul>
      <li><a href="#cd">Character Description</a></li>
      <li><a href="#abilities">Abilities</a></li>
      <li><a href="#cs">Combat Stats</a></li>
      <ul>
       <li><a href="#cs_hp">Hit Points</a></li>
       <li><a href="#cs_ac">Armor Class</a></li>
       <li><a href="#cs_initiative">Initiative</a></li>
       <li><a href="#cs_other">Other Stats</a></li>
      </ul>
      <li><a href="#saves">Saving Throws</a></li>
      <li><a href="#ab">Attack Bonuses</a></li>
      <li><a href="#weapons">Weapons</a></li>
      <li><a href="#ammunition">Ammunition</a></li>
      <li><a href="#defensives">Armor/Protective Items</a></li>
      <li><a href="#skills">Skills</a></li>
      <li><a href="#gear">Gear</a></li>
      <li><a href="#money">Money</a></li>
      <li><a href="#feats">Feats</a></li>
      <li><a href="#weight">Weight</a></li>
      <li><a href="#languages">Languages</a></li>
      <li><a href="#spells">Spells</a></li>
      <ul>
       <li><a href="#dailyspells">Daily Spells</a></li>
       <li><a href="#domainspells">Domain Spells</a></li>
       <li><a href="#spellsaves">Spell Saving Throws</a></li>
      </ul>
     </ul>
    </ul>
   <?php
    enddiv();
    hprint(2, "cd", "Character Description");
    newdiv("cd");
    #pstdaction();
   ?>
    <!--ACTION: Update (Confirms.)-->
    <!--TRACKED: Name-->
    <?php
     ptrack("Name", "cd_name");
    ?>
    <!--TRACKED: Class-->
    <?php
     ptrack("Class", "cd_class");
    ?>
    <!--TRACKED: Race-->
    <?php
     ptrack("Race", "cd_race");
    ?>
    <!--TRACKED: order alignment-->
    <?php
     ptrack("Order Alignment (Lawful/Neutral/Chaotic", "cd_order_alignment");
    ?>
    <!--TRACKED: moral alignment-->
    <?php
     ptrack("Moral Alignment (Evil/Neutral/Good)", "cd_moral_alignment");
    ?>
    <!--TRACKED: Diety-->
    <?php
     ptrack("Diety", "cd_diety");
    ?>
    <!--TRACKED: Level-->
    <?php
     ptrack("Level", "cd_level");
    ?>
    <!--TRACKED: Size-->
    <?php
     $cd_size = get_var('cd_size');
     global $pmc;

     gprint("<span class=\"field_label\">Size: ");

     if (($cd_size) or (get_var('cd_size_choose'))) {
      
      if (!($cd_size)) {
       $cd_size = 4;
      }
      
      gprint("<select name=\"cd_size\">");
 
      $pmc++;
      
      for ($size_index = $cd_sizes['lower']; $size_index < $cd_size; $size_index++) {
       gprint("<option value=\"$size_index\">" . $cd_sizes[$size_index]['name'] . "</option>");
      }
 
      gprint("<option value=\"$cd_size\" selected>" . $cd_sizes[$cd_size]['name'] . "</option>");
 
      for ($size_index = $cd_size + 1; $size_index < $cd_sizes['upper']; $size_index++) {
       gprint("<option value=\"$size_index\">" . $cd_sizes[$size_index]['name'] . "</option>");
      }
 
      $pmc--;

      gprint("</select>");
     } else {
      psubmit("Choose Value", 'cd_size_choose');
     }

     gprint ("<br><br>");

    ?>
    <!--TRACKED: Age-->
    <?php
     ptrack("Age", "cd_age");
    ?>
    <!--TRACKED: Gender-->
    <?php
     ptrack("Gender", "cd_gender");
    ?>
    <!--TRACKED: Height-->
    <?php
     ptrack("Height", "cd_height");
    ?>
    <!--TRACKED: Weight-->
    <?php
     ptrack("Weight", "cd_weight");
    ?>
    <!--TRACKED: Eyes-->
    <?php
     ptrack("Eye Color", "cd_eyecolor");
    ?>
    <!--TRACKED: Hair-->
    <?php
     ptrack("Hair Color", "cd_haircolor");
    ?>
   <?php
    enddiv();
    hprint(2, "abilities", "Abilities");
    newdiv("abilities");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
     <!--UPDATES: Combat Stats-->
     <!--UPDATES: Initiative-->
     <!--UPDATES: Saving Throws-->
    <!--UPDATES: Attack Bonuses-->
    <!--AUTOGEN: list(STR, DEX, CON, INT, WIS, CHA)-->
     <!--CALCULATED: Ability Score-->
      <!--DEPENDS: Base Score-->
      <!--DEPENDS: Score Modifiers-->
     <!--CALCULATED: Ability Modifier-->
      <!--DEPENDS: Ability Score-->
     <!--TRACKED: Base Score-->
     <!--ACTION: Add Ability Modifier-->
     <!--AUTOGEN: Ability Score Modifiers-->
      <!--TRACKED: Source-->
      <!--TRACKED: Value-->
      <!--ACTION: Remove (confirm)-->
    <?php
     abilitygen("STR");
     abilitygen("DEX");
     abilitygen("CON");
     abilitygen("INT");
     abilitygen("WIS");
     abilitygen("CHA");
     enddiv();
     hprint(2, "cs", "Combat Stats");
     newdiv("cs");
     hprint(3, "cs_hp", "Hit Points (HP)");
     newdiv("cs_hp");
     #pstdaction();
    ?>
      <!--ACTION: Update-->
      <!--CALCULATED: Total HP-->
       <!--DEPENDS: Base HP-->
       <!--DEPENDS: Wounds-->
       <!--DEPENDS: Subdual Damage-->
      <!--CALCULATED: Mortal Status (Alive, Staggered, Unconscious, Dead)-->
       <!--DEPENDS: Base HP-->
       <!--DEPENDS: Wounds-->
       <!--DEPENDS: Subdual Damage-->
      <!--CALCULATED: Time to DEATH (How many rounds/seconds until -10 reached)-->
       <!--DEPENDS: Base HP-->
       <!--DEPENDS: Wounds-->
       <!--DEPENDS: Subdual Damage-->
      <!--TRACKED:Base HP-->
    <?php
     pebug_set('hp code');
     $cs_hp_base = get_var("cs_hp_base");
     $cs_hp_lethal_damage = get_var("cs_hp_lethal_damage");
     $cs_hp_subdual_damage = get_var("cs_hp_subdual_damage");

     $cs_hp_adjust_lethal = get_var("cs_hp_adjust_lethal");
     $cs_hp_adjust_subdual = get_var("cs_hp_adjust_subdual");
     $cs_hp_heal = get_var("cs_hp_heal");
     
     if ($cs_hp_adjust_lethal > 0) {
      pebug("Applying Lethal Damage");
      $cs_hp_lethal_damage += $cs_hp_adjust_lethal;
     }

     if ($cs_hp_adjust_subdual > 0) {
      pebug("Applying Subdual Damage");
      $cs_hp_subdual_damage += $cs_hp_adjust_subdual;
     }

     if ($cs_hp_heal > 0) {
      pebug("Applying Healing");
      $cs_hp_lethal_damage -= $cs_hp_heal;
      if ($cs_hp_lethal_damage < 0) {
       $cs_hp_lethal_damage = 0;
      }
     }

     if (get_var('cs_hp_curesubdual')) {
      $cs_hp_subdual_damage = 0;
     }

     function add_status_list ($list, $status){
      if ($list) {
       $list .= ", $status";
      } else {
       $list = $status;
      }

      return $list;
     }

     $cs_hp_available = $cs_hp_base - $cs_hp_lethal_damage - $cs_hp_subdual_damage;
     if ($cs_hp_available < 0) {
      $cs_hp_status = add_status_list ($cs_hp_status, "Unconscious");
     }

     if ($cs_hp_base == $cs_hp_lethal_damage) {
      $cs_hp_status = add_status_list ($cs_hp_status, "Disabled");
     }

     if (($cs_hp_subdual_damage == ($cs_hp_base - $cs_hp_lethal_damage)) && ($cs_hp_subdual_damage > 0)) {
      $cs_hp_status = add_status_list ($cs_hp_status, "Staggered");
     }

     if ($cs_hp_available > 0) {
      $cs_hp_status = add_status_list ($cs_hp_status, "Healthy");
     }

     if (($cs_hp_base - $cs_hp_lethal_damage) <= -10) {
      # Being dead supercedes all other statuses.
      $cs_hp_status = "DEAD";
     }

     if ($cs_hp_base) {
      print_field("calculated_field", "Base HP", $cs_hp_base);
      print_field("calculated_field", "Lethal Damage", $cs_hp_lethal_damage);
      print_field("calculated_field", "Subdual Damage", $cs_hp_subdual_damage);
      print_field("calculated_field", "Status", $cs_hp_status);
     }

     ptrack("Base HP", "cs_hp_base");

     if ($cs_hp_base) {
      if (get_var("cs_hp_modify")) {
       ptext("Lethal Damage", "cs_hp_adjust_lethal");
       ptext("Subdual Damage", "cs_hp_adjust_subdual");
       ptext("Heal", "cs_hp_heal");
 
       psubmit("Apply Damage/Healing", "cs_hp_adjust");
       psubmit("Cure Subdual Damage", "cs_hp_curesubdual");
      } else {
       psubmit("Modify HP", "cs_hp_modify");
      }
     }

     store_numvar("cs_hp_lethal_damage", $cs_hp_lethal_damage);
     store_numvar("cs_hp_subdual_damage", $cs_hp_subdual_damage);

     pebug_restore();
    ?>
      <!--TRACKED:Wounds-->
      <!--ACTION:Apply Damage-->
       <!--DEPENDS: Damage Reduction-->
      <!--ACTION:Apply Subdual Damage-->
       <!--DEPENDS: Damage Reduction-->
      <!--ACTION:Heal-->
     <?php
      enddiv();
      hprint(3, "cs_ac", "Armor Class");
      newdiv("cs_ac");
      #pstdaction();
     ?>
      <!--ACTION: Update-->
      <!--CALCULATED: Total AC-->
       <!--DEPENDS: Aggregate Defensive Bonus-->
       <!--DEPENDS: DEX Ability Bonus-->
       <!--DEPENDS: Size Modifier-->
       <!--DEPENDS: Natural Armor-->
       <!--DEPENDS: Aggregate AC Modifiers-->
      <!--TRACKED: Size Modifier-->
      <?php
       ptrack("Size Modifier", "cs_ac_size_modifier");
      ?>
      <!--TRACKED: Natural Armor-->
      <?php
       ptrack("Natural Armor Bonus", "cs_ac_natural_armor");
      ?>
      <!--ACTION: Add Misc Modifier-->
      <!--AUTOGEN: Misc Modifiers-->
       <!--TRACKED: Name-->
       <!--TRACKED: Value-->
       <!--MODIFIES: Aggregate AC Modifier-->
       <!--ACTION: Remove-->
     <?php
      enddiv();
      hprint(3, "cs_initiative", "Initiative");
      newdiv("cs_initiative");
      #pstdaction();
     ?>
      <!--ACTION: Update-->
      <!--ACTION: Roll Initiative-->
       <!--DEPENDS: DEX Ability Bonus-->
       <!--DEPENDS: Aggregate Initiative Modifiers-->
      <?php

      ?>
      <!--TRACKED: Base Attack Bonus-->
      <?php
       ptrack("Base Attack Bonus", "cs_base_attack_bonus");
       
       # Initiative Modifier variables
       $im_count = get_var("im_count");
       $addim="addim";
       $addimvalue="newimvalue";
       $addimsource="newimsource";
       $im_index_offset = 0;

       # Iterate through all the known modifiers.
       for ($im_index=1; $im_index <= $im_count; $im_index++):
        $im_index_modified= $im_index + $im_index_offset;
        $im_original_id = "im_$im_index";
        $im_new_id = "im_$im_index_modified";
        $imvaluevar = "im_value_$im_original_id";
        $imsourcevar = "im_source_$im_original_id";
        $imvalue = get_var($imvaluevar);
        $imsource = get_var($imsourcevar);
        $removeim = "remove_$im_original_id";

        # Weed out any selected for removal.
        if (get_var($removeim)) {
         $im_index_offset--;
        } else {
         $imvaluevar = "im_value_$im_new_id";
         $imsourcevar = "im_source_$im_new_id";
         $removeim = "remove_$im_new_id";
      
         # Store any retained in the amm array.
         $IM["removeim$im_new_id"] = $removeim;
         $IM["imvaluevar$im_new_id"] = $imvaluevar;
         $IM["imvalue$im_new_id"] = $imvalue;
         $IM["imsourcevar$im_new_id"] = $imsourcevar;
         $IM["imsource$im_new_id"] = $imsource;
        }
       endfor;

       #If they filled in the field to add a new modifier...
       if (get_var($addimvalue)) {
        $im_index_modified= $im_index + $im_index_offset;
        $im_id = "im_$im_index_modified";
        $imvaluevar = "im_value_$im_id";
        $imsourcevar = "im_source_$im_id";
        $imvalue = get_var($addimvalue);
        $imsource = get_var($addimsource);
        $removeim = "remove_$im_id";
     
        $IM["removeim$im_id"] = $removeim;
        $IM["imvaluevar$im_id"] = $imvaluevar;
        $IM["imvalue$im_id"] = $imvalue;
        $IM["imsourcevar$im_id"] = $imsourcevar;
        $IM["imsource$im_id"] = $imsource;
     
        # We now have one more modifier.
        $im_count++;
       }
       $im_count += $im_index_offset;

       # Calculate the total Initiative Bonus

       $initiative_bonus = 0;
       
       for ($im_index = 1; $im_index <= $im_count; $im_index++):
        $im_id = "im_$im_index";
        $imvalue = $IM["imvalue$im_id"];

	$initiative_bonus += $imvalue;
       endfor;

       # Print Initiative bonus calculations, if there are any.
       $im_id = "im_1";
       if ($IM["imvalue$im_id"]) {
        print_field("calculated_field", "Total Initiative Modifier", $initiative_bonus);
	$im_id = "im_1";
        $imvalue = $IM["imvalue$im_id"];
	$imsource = $IM["imsource$im_id"];
	$removeim = $IM["removeim$im_id"];
	$imvaluevar = $IM["imvaluevar$im_id"];
	$imsourcevar = $IM["imsourcevar$im_id"];

	print "<input type=\"submit\" name=\"$removeim\" value=\"$imvalue ($imsource)\">";
	store_var($imvaluevar, $imvalue);
	store_var($imsourcevar, $imsource);
        
	for ($im_index = 2; $im_index <= $im_count; $im_index++):
         $im_id = "im_$im_index";
         $imvalue = $IM["imvalue$im_id"];
	 $imsource = $IM["imsource$im_id"];
	 $imvaluevar = $IM["imvaluevar$im_id"];
	 $imsourcevar = $IM["imsourcevar$im_id"];
	 $removeim = $IM["removeim$im_id"];

         print " + <input type=\"submit\" name=\"$removeim\" value=\"$imvalue ($imsource)\">";
	store_var($imvaluevar, $imvalue);
	store_var($imsourcevar, $imsource);
        endfor;
       }

       psubmit('Add Initiative Modifier', $addim);

       if (get_var($addim)) {
        newdiv("im_mod_outer");
        newdiv("im_mod_inner");
 
        print "     New <em>Initiative</em> Modifier: <input type=\"text\" name=\"$addimvalue\"><br/>\n";
        print "     Source of new <em>Initiative</em> Modifier: <input type=\"text=\" name=\"$addimsource\"><br/>\n";
        print "     <input type=\"submit\" value=\"Add Modifier\"><br/>\n";
 
        enddiv();
        enddiv();
       }

       # Save out Modifier count
       store_numvar("im_count", $im_count);
      ?>
      <!--ACTION: Add Initiative Modifier-->
      <!--AUTOGEN: Initiative Modifiers-->
       <!--TRACKED: Name-->
       <!--TRACKED: Value-->
       <!--MODIFIES: Aggregate Initiative Modifier-->
       <!--ACTION: Remove-->
    <?php
     enddiv();
     hprint(2, "cs_other", "Other Stats");
     newdiv("cs_other");
     #pstdaction();
    ?>
     <!--ACTION: Update-->
     <!--TRACKED: Damage reduction-->
     <?php
      ptrack("Damage Reduction", "cs_damage_reduction");
     ?>
     <!--TRACKED: Hit die type-->
     <?php
      ptrack("Hit Die (HD)", "cs_hit_die");
     ?>
     <!--TRACKED: Base Speed-->
     <?php
      ptrack("Race Speed", "cs_base_speed");
     ?>
     <!--CALCULATED: Current Speed-->
      <!--DEPENDS: Armor Speed Modifier-->
     <!--CALCULATED: Miss Chance-->
      <!--DEPENDS: Aggregate Miss Chance-->
     <!--CALCULATED: Armor Check Penalty-->
      <!--DEPENDS: Aggregate ACP-->
     <!--CALCULATED: Spell Resistance-->
      <!--DEPENDS: Aggregate Spell Resistance-->
   <?php
    enddiv();
    enddiv();
    hprint(2, "saves", "Saving Throws");
    newdiv("saves");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--AUTOGEN: stlist(Fortitude+CON, Reflex+DEX, Will+WIS)-->
     <!--ACTION: Roll Save-->
      <!--DEPENDS: Total Bonus-->
     <!--CALCULATED: Total Bonus-->
      <!--DEPENDS: Base Save-->
      <!--DEPENDS: Ability Modifier-->
      <!--DEPENDS: Aggregate (TYPE) Modifier-->
     <!--TRACKED: Base Save-->
     <!--ACTION: Add Save Modifier-->
     <!--AUTOGEN: per-save-modifier-->
      <!--TRACKED: Source-->
      <!--TRACKED: Value-->
      <!--MODIFIES: Aggregate (TYPE) Modifier-->
      <!--ACTION: Remove (Confirms twice)-->
   <?php
    enddiv();
    hprint(2, "ab", "Attack Bonuses");
    newdiv("ab");
    #pstdaction();
   ?>
    <!--Update-->
    <!--AUTOGEN: ablist(Melee+STR, Ranged+DEX-->
     <!--CALCULATED: Total (TYPE) Attack Bonus-->
      <!--DEPENDS: Base Attack Bonus-->
      <!--DEPENDS: Ability Modifier-->
      <!--DEPENDS: Size Modifier-->
      <!--DEPENDS: Aggregate (TYPE) Attack Bonus Modifier-->
     <!--ACTION: Add Modifier-->
     <!--AUTOGEN: per-modifier-->
      <!--TRACKED: Source-->
      <!--TRACKED: Value-->
      <!--MODIFIES: Aggregate (TYPE) Attack Bonus Modifier-->
      <!--ACTION: Remove (confirms twice)-->
   <?php
    enddiv();
    hprint(2, "weapons", "Weapons");
    newdiv("weapons");
    #pstdaction();
   ?>
    <!--UPDATE-->
    <!--OPTION: section global: Trackweight-->
    <!--ACTION: Add Weapon-->
    <!--AUTOGEN: per-weapon-->
     <!--TRACKED: Name-->
     <!--CALCULATED: Unique Attack Bonus-->
      <!--DEPENDS: Attack Type-->
      <!--DEPENDS: Total (TYPE) Attack Bonus-->
      <!--DEPENDS: Unique Attack Bonus Modifier-->
     <!--TRACKED: Unique Attack Bonus Modifier-->
     <!--TRACKED: Damage die-->
     <!--TRACKED: Damage die count-->
     <!--CHOICE: Critical Range: 19-20, 20-->
     <!--TRACKED: Range Increment-->
     <!--TRACKED: Weight-->
     <!--TRACKED: Damage Type-->
     <!--CHOICE: Attack Type Melee, Ranged-->
     <!--TRACKED: Size-->
     <!--TRACKED: Special Properties-->
     <!--TRACKED: AmmoID-->
     <!--ACTION: per-weapon: Attack (Rolls attack and damage, subtracts from ammo.-->
      <!--DEPENDS: Unique Attack Bonus-->
      <!--DEPENDS: AmmoID-->
      <!--DEPENDS: Damage die-->
      <!--DEPENDS: Damage die count-->
      <!--DEPENDS: Attack Type-->
      <!--DEPENDS: Critical Range-->
      <!--DEPENDS: Range Increment-->
     <!--PROMPT: Range to target-->
      <!--MODIFIES: Ammo qty per AmmoID-->
      <!--UPDATES: Ammunition-->
     <!--ACTION: per-weapon: Remove Weapon (Confirms twice)-->
      <!--MODIFIES: Aggregate Weapon Weight-->
    <?php
     hprint(3, "ammunition", "Ammunition");
     newdiv("ammunition");
     #pstdaction();
    ?>
     <!--ACTION: Update-->
     <!--OPTION: section global: Trackweight-->
     <!--ACTION: Add new ammo-->
     <!--AUTOGEN: per-ammo-->
      <!--TRACKED: Name-->
      <!--TRACKED: Weight per ten-->
      <!--TRACKED: Quantity-->
      <!--TRACKED: AmmoID-->
      <!--TRACKED: special properties-->
      <!--ACTION: Add X number-->
       <!--MODIFIES: Quantity-->
      <!--ACTION: Remove X number-->
       <!--MODIFIES: Quantity-->
      <!--UPDATES: Ammunition-->
   <?php
    enddiv();
    enddiv();
    hprint(2, "defensives", "Shield, Armor, etc.");
    newdiv("defensives");
    #pstdaction();

    #Data storage format for defensives:
    # defensive_trackweight
    # defensive_count: how many defensive items are currently tracked.

    $defensive_count = get_var('defensive_count');

    #Iterate through the known defensives.
    for ($defensive_index = 1; $defensive_index <= $defensive_count; $defensive_index++) {
     $dprefix = "defensive_" . $defensive_index . "_";
     if (get_var($dprefix . 'remove')) {
      $defensives_removed++;
     } else {
      $dfo = $defensive_index - $defensives_removed;
      $defensives[$dfo]['name'] = get_var($dprefix . 'name');
      $defensives[$dfo]['type'] = get_var($dprefix . 'type');
      $defensives[$dfo]['acb'] = get_var($dprefix . 'acb');
      $defensives[$dfo]['mdb'] = get_var($dprefix . 'mdb');
      $defensives[$dfo]['cp'] = get_var($dprefix . 'cp');
      $defensives[$dfo]['sfc'] = get_var($dprefix . 'sf');
      $defensives[$dfo]['speed'] = get_var($dprefix . 'speed');
      $defensives[$dfo]['weight'] = get_var($dprefix . 'weight');
      $defensives[$dfo]['sp'] = get_var($dprefix . 'sp');
      $defensives[$dfo]['remove'] = $dprefix . 'remove';

      store_var('defensive_' . $dfo . '_name', $defensives[$dfo]['name']);
      store_var('defensive_' . $dfo . '_type', $defensives[$dfo]['type']);
      store_var('defensive_' . $dfo . '_acb', $defensives[$dfo]['acb']);
      store_var('defensive_' . $dfo . '_mdb', $defensives[$dfo]['mdb']);
      store_var('defensive_' . $dfo . '_cp', $defensives[$dfo]['cp']);
      store_var('defensive_' . $dfo . '_sf', $defensives[$dfo]['sfc']);
      store_var('defensive_' . $dfo . '_speed', $defensives[$dfo]['speed']);
      store_var('defensive_' . $dfo . '_weight', $defensives[$dfo]['weight']);
      store_var('defensive_' . $dfo . '_sp', $defensives[$dfo]['sp']);

     }
    }
    $defensive_count -= $defensives_removed;

    if (get_var('adddefensive_name')) {
     pebug("Adding defensive");
     $defensive_count++;
     $dprefix = 'adddefensive_';
     $defensives[$defensive_count]['name'] = get_var($dprefix . 'name');
     $defensives[$defensive_count]['type'] = get_var($dprefix . 'type');
     $defensives[$defensive_count]['acb'] = get_var($dprefix . 'acb');
     $defensives[$defensive_count]['mdb'] = get_var($dprefix . 'mdb');
     $defensives[$defensive_count]['cp'] = get_var($dprefix . 'cp');
     $defensives[$defensive_count]['sfc'] = get_var($dprefix . 'sf');
     $defensives[$defensive_count]['speed'] = get_var($dprefix . 'speed');
     $defensives[$defensive_count]['weight'] = get_var($dprefix . 'weight');
     $defensives[$defensive_count]['sp'] = get_var($dprefix . 'sp');
     $defensives[$defensive_count]['remove'] = $dprefix . 'remove';

     store_var('defensive_' . $defensive_count . '_name', $defensives[$defensive_count]['name']);
     store_var('defensive_' . $defensive_count . '_type', $defensives[$defensive_count]['type']);
     store_var('defensive_' . $defensive_count . '_acb', $defensives[$defensive_count]['acb']);
     store_var('defensive_' . $defensive_count . '_mdb', $defensives[$defensive_count]['mdb']);
     store_var('defensive_' . $defensive_count . '_cp', $defensives[$defensive_count]['cp']);
     store_var('defensive_' . $defensive_count . '_sf', $defensives[$defensive_count]['sfc']);
     store_var('defensive_' . $defensive_count . '_speed', $defensives[$defensive_count]['speed']);
     store_var('defensive_' . $defensive_count . '_weight', $defensives[$defensive_count]['weight']);
     store_var('defensive_' . $defensive_count . '_sp', $defensives[$defensive_count]['sp']);

    }

    # Do some calculations required for every defensive pieces of equipment.
    for ($defensive_index = 1; $defensive_index <= $defensive_count; $defensive_index++) {
     pebug_set("Defensive_equip: $defensive_index");
     $equipname = 'defensive_' . $defensive_index . 'equip';
     $unequipname = 'defensive_' . $defensive_index . 'unequip';
     $defensive_type = $defensives[$defensive_index]['type'];
     pebug("Saw type $defensive_type"); 

     if (get_var($equipname)) {
      # The Equip button for this item was selected.
      pebug("Detected EQUIP Action");

      # We need to unequip all other items of the same general type.
      if ($defensive_type < 4) {
       for ($inner_index = 1; $inner_index <= $defensive_count; $inner_index++) {
        $inner_type = $defensives[$inner_index]['type'];
        if (($inner_type == 0) && ($defensive_type == 0)) {
	 $defensives[$inner_index]['equipped'] = false;
	} elseif (($inner_type < 4) && ($defensive_type != 0)) {
	 $defensives[$inner_index]['equipped'] = false;
	}
       }
      }

      # And a flag for the next stage.
      $isequipped = true;
     } elseif (get_var($unequipname)) {
      # The UnEquip button for this item was selected.
      $isequipped = false;
     } else {
      # equipped status reverts back to previous.
      $isequipped = get_var('defensive_' . $defensive_index . '_equipped');
     }

     # And some preparations based on the equipped/unequipped result.

     if ($isequipped) {
      $defensives[$defensive_index]['eulabel'] = "Unequip";
      $defensives[$defensive_index]['euname'] = $unequipname;
     } else {
      $defensives[$defensive_index]['eulabel'] = "Equip";
      $defensives[$defensive_index]['euname'] = $equipname;
     }
     $defensives[$defensive_index]['equipped'] = $isequipped;

     # And now to check for held status.
     $defensive_hold = 'defensive_' . $defensive_index . 'hold';
     $defensive_drop = 'defensive_' . $defensive_index . 'drop';
     $defensive_held = 'defensive_' . $defensive_index . '_held';

     if(get_var($defensive_hold)){
      $heldstatus = true;
     } elseif (get_var($defensive_drop)) {
      $heldstatus = false;
     } else {
      $heldstatus = get_var($defensive_held);
     }

     if($heldstatus == true) {
      $defensives[$defensive_index]['hdlabel'] = "Drop";
      $defensives[$defensive_index]['hdname'] = $defensive_drop;
     } elseif ($heldstatus == false) {
      $defensives[$defensive_index]['hdlabel'] = "Hold";
      $defensives[$defensive_index]['hdname'] = $defensive_hold;
     }

     $defensives[$defensive_index]['held'] = $heldstatus;
     pebug_restore();
    }

    store_numvar('defensive_count', $defensive_count);

    $dtypetext[0] = "Shield";
    $dtypetext[1] = "Heavy Armor";
    $dtypetext[2] = "Medium Armor";
    $dtypetext[3] = "Light Armor";
    $dtypetext[4] = "Other";
    $dtypetext['lower'] = 0;
    $dtypetext['upper'] = 4;

    # Time for output.

    for ($defensive_index = 1; $defensive_index <= $defensive_count; $defensive_index++) {
     $dname = $defensives[$defensive_index]['name'];
     $dtype = $defensives[$defensive_index]['type'];
     $dacb = $defensives[$defensive_index]['acb'];
     $dmdb = $defensives[$defensive_index]['mdb'];
     $dcp = $defensives[$defensive_index]['cp'];
     $dsfc = '%' . ($defensives[$defensive_index]['sfc'] * 100);
     $dspeed = $defensives[$defensive_index]['speed'];
     $dweight = $defensives[$defensive_index]['weight'];
     $dsp = $defensives[$defensive_index]['sp'];
     newdiv("defensive_outer");
     newdiv("defensive_inner");

     hprint(3, "defensive$defensive_index", $dname . ' [' . $dtypetext[$dtype] . ']');
     
     if ($defensives[$defensive_index]['held'] == false) {
      newdiv("defensive_unheld");
     } elseif ($defensives[$defensive_index]['equipped'] == true) {
      newdiv("defensive_equipped");
     } else {
      newdiv("defensive_unequipped");
     }

     print_field("stored_field", 'AC Bonus', $dacb);
     print_field("stored_field", 'Max DEX Bonus', $dmdb);
     print_field("stored_field", 'Check Penalty', $dcp);
     print_field("stored_field", 'Spell Failure Chance', $dsfc);
     print_field("stored_field", 'Max Character Speed', $dspeed);
     print_field("stored_field", 'Item weight', $dweight);
     print_field("stored_field", 'Special Properties', $dsp);

     enddiv();

     if ($defensives[$defensive_index]['held'] == true) {
      psubmit($defensives[$defensive_index]['eulabel'], $defensives[$defensive_index]['euname']);
     }
     psubmit($defensives[$defensive_index]['hdlabel'], $defensives[$defensive_index]['hdname']);
     psubmit("Destroy", $defensives[$defensive_index]['remove']);

     store_var('defensive_' . $defensive_index . '_equipped', $defensives[$defensive_index]['equipped']);
     store_var('defensive_' . $defensive_index . '_held', $defensives[$defensive_index]['held']);
    
     enddiv();
     enddiv();
      
    }

    psubmit("Add Defensive Equipement", 'adddefensive');

    if (get_var('adddefensive')) {

     newdiv("add_defensive_outer");
     newdiv("add_defensive_inner");
     
     # Get name
     ptext('Name', 'adddefensive_name');
     # Get Type
     gprint ("<span class=\"ptext\">Type: <select name=\"adddefensive_type\">");
     $pmc++;
     for ($typeindex = $dtypetext['lower']; $typeindex <= $dtypetext['upper']; $typeindex++) {
      gprint("<option value=\"$typeindex\">" . $dtypetext[$typeindex] . "</option>");
     }
     $pmc--;
 
     gprint("</select></span><br/>");
 
     # Get AC Bonus
     ptext('AC Bonus', 'adddefensive_acb');
     # Get Max DEX Bonus
     ptext('Max DEX Bonus', 'adddefensive_mdb');
     # Get Check Penalty
     ptext('Check Penalty', 'adddefensive_cp');
     # Get Spell Failure Chance
     ptext('Spell Failure Chance', 'adddefensive_sfc');
     # Get Speed Reduction
     ptext('Speed Reduction', 'adddefensive_speed');
     # Get Item Weight
     ptext('Item Weight', 'adddefensive_weight');
     # Get Special Properties
     ptextarea('Special Properties', 'adddefensive_sp');
 
     psubmit('Add Equipment', 'submit');
 
 
     enddiv();
     enddiv();

    }
    
    # defensive_N_remove -- Action: Remove this defensive.
    # defensive_N_name -- Name of defensive
    # defensive_N_type -- type (Shield, Light armor, medium armor, heavy armor, other)
    # defensive_N_acb -- AC Bonus
    # defensive_N_mdb -- Max dex bonus
    # defensive_N_cp -- Check Penalty
    # defensive_N_sfc -- Spell Failure chance
    # defensive_N_speed -- Speed reduction
    # defensive_N_weight -- Item weight
    # defensive_N_sp -- Special properties
    # defensive_N_equipped -- Is the item equipped?
    # defensive_N_held -- Is the item even held? (Useful in case the item falls out of the character's posession, but the player doesn't want to re-enter the data later.)
   ?>
    <!--ACTION: Update-->
    <!--ACTION: Add Defensive-->
    <!--OPTION: section global: Trackweight-->
    <!--AUTOGEN: per-defensive-->
     <!--TRACKED: Name-->
     <!--TRACKED: Defense type-->
     <!--CHOICE: Type (Shield/other, light, medium, heavy)-->
     <!--TRACKED: AC bonus-->
     <!--TRACKED: Max Dex Bonus-->
     <!--TRACKED: Check Penalty-->
     <!--TRACKED: Spell Failure-->
     <!--TRACKED: Speed-->
     <!--TRACKED: Weight-->
     <!--TRACKED: Special Properties-->
   <?php
    enddiv();
    hprint(2, "skills", "Skills");
    newdiv("skills");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--TRACKED: section global: max ranks class,crossclass-->
    <!--ACTION: Add Skill-->
    <!--AUTOGEN: per-skill-->
     <!--TRACKED: Name-->
     <!--TRACKED: crossclass-->
     <!--CHOICE: key ability (STR, DEX, CON, INT, WIS, CHA)-->
     <!--TRACKED: ranks-->
     <!--TRACKED: misc modifier-->
     <!--OPTION: ACP applies-->
     <!--OPTION: usednormally-->
     <!--OPTION: isswim-->
     <!--ACTION: Skill check (Rolls d20 and applies skill modifier)-->
      <!--DEPENDS: Ability Modifier-->
      <!--DEPENDS: Ranks-->
      <!--DEPENDS: Misc Modifier-->
      <!--DEPENDS: Armor Check Penalty-->
      <!--DEPENDS: Used Normally -->
      <!--DEPENDS: Is Swim-->
     <!--ACTION: Remove Skill-->
   <?php
    enddiv();
    hprint(2, "gear", "Gear");
    newdiv("gear");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--OPTION: section global: Trackweight-->
    <!--ACTION: Add Gear-->
    <!--AUTOGEN: per-gear-->
     <!--TRACKED: per-gear: Name, qty, Weight-->
     <!--ACTION: per-gear: Remove-->
   <?php
    enddiv();
    hprint(2, "money", "Money");
    newdiv("money");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--OPTION: section global: Trackweight-->
    <!--CALCULATED: Money weight-->
     <!--DEPENDS: Aggregate Qty-->
    <!--AUTOGEN: per-moneytype-->
     <!--TRACKED: per-monetype: Quantity-->
     <!--ACTION: per-moneytype: Add-->
      <!--MODIFiES: Quantity-->
      <!--MODIFIES: Aggregate Qty-->
     <!--ACTION: per-moneytype: Subtract-->
      <!--MODIFIES: Quantity-->
      <!--MODIFIES: Aggregate Qty-->
   <?php
    enddiv();
    hprint(2, "feats", "Special Abilities/Feats");
    newdiv("feats");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--CONDITIONAL DIVISION: Turn/Rebuke-->
<?php
     newdiv("turn_rebuke");
?>
     <!--Turning Level-->
     <!--CALCULATED: Turn/Rebuke Attempts available/day-->
      <!--DEPENDS: CHA ability modifier-->
     <!--TRACKED: Turn/Rebuke Attempts used-->
     <?php
      ptrack("Attempts Used", "cs_feats_tr_used");
     ?>
     <!--ACTION: Attempt turn/Rebuke (rolls d20, applies CHA modifier, reports modifiedroll, highest HD character can turn, and number of HD character can turn.-->
      <!--DEPENDS: Attempts available-->
      <!--DEPENDS: Attempts used-->
      <!--DEPENDS: CHA ability modifier-->
      <!--DEPENDS: Character Level-->
     <!--ACTION: Replenish (Resets Used to 0)-->
<?php
    enddiv();
?>
    <!--ACTION: Add Feat-->
    <!--AUTOGEN: per-feat-->
     <!--TRACKED: per-feat: name-->
     <!--CHOICE: Replenished daily/weekly/infinite uses-->
     <!--CONDITIONAL DIVISION: Noninfinite-->
      <!--TRACKED: Max Uses-->
      <!--TRACKED: Used-->
      <!--ACTION: Replenish (Resets Used to 0)-->
     <!--ACTION: Remove Feat-->
   <?php
    enddiv();
    hprint(2, "weight", "Weight Load");
    newdiv("weight");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--CALCULATED: Light load-->
     <!--DEPENDS: STR Ability Score-->
     <!--DEPENDS: Character Size-->
    <!--CALCULATED: Medium load-->
     <!--DEPENDS: STR Ability Score-->
     <!--DEPENDS: Character Size-->
    <!--CALCULATED: Heavy load-->
     <!--DEPENDS: STR Ability Score-->
     <!--DEPENDS: Character Size-->
    <!--CALCULATED: Lift Over Head-->
     <!--DEPENDS: Heavy Load-->
    <!--CALCULATED: Lift Off Ground-->
     <!--DEPENDS: Heavy Load-->
     <!--x2-->
    <!--CALCULATED: Push or Drag-->
     <!--DEPENDS: Heavy Load-->
     <!--x5-->
   <?php
    enddiv();
    hprint(2, "languages", "Languages");
    newdiv("languages");
    #pstdaction();
   ?>
    <!--ACTION: Update-->
    <!--ACTION: Add Language-->
    <!--AUTOGEN: per-language-->
     <!--TRACKED: name-->
     <!--ACTION: Remove (Confirms twice)-->
   <?php
    enddiv();
    hprint(2, "spells", "Spells");
    newdiv("spells");
   ?>
   <!--CONDITIONAL DIVISION: Spellcaster-->
<?php
   hprint(2, "dailyspells", "Daily Arcane/Divine Spells");
   newdiv("spellcaster");
   #pstdaction();
?>
     <!--ACTION: Update-->
      <!--LOOPGEN: per-spell-level, 0-9-->
       <!--ACTION: Add spell-->
       <!--AUTOGEN: per-spell-->
        <!--TRACKED: Name-->
        <!--TRACKED: Meta-Magic Feats-->
        <!--TRACKED: Domain level modifier-->
        <!--ACTION: Add Meta-Magic Feat (Reminds user that adding a Meta-Magic Feat usually increases a spell's level)-->
        <!--ACTION: Remove Meta-Magic Feat (Confirms twice)-->
        <!--ACTION: Cast (May disable cast button, Suggests concentration check)-->
         <!--DEPENDS: Spells per Day @ (LEVEL)-->
        <!--ACTION: Remove (Confirms twice)-->
     <!--CONDITIONAL DIVISION: Domain Spellcaster-->
<?php
     enddiv();
     hprint(2, "domaincaster", "Domain Spells");
     newdiv("domaincaster");
     #pstdaction();
?>
       <!--ACTION: Update-->
       <!--ACTION: Add spell domain-->
       <!--AUTOGEN: per-domain-->
        <!--TRACKED: Name-->
        <!--TRACKED: granted power-->
        <!--LOOPGEN: per-level, 1-9-->
         <!--TRACKED: name-->
         <!--ACTION: Add Meta-Magic Feat (Reminds user that adding a Meta-Magic Feat usually increases a spell's level)-->
         <!--ACTION: Remove Meta-Magic Feat (Confirms twice)-->
         <!--ACTION: Cast (Disables cast button, Suggests concentration check)-->
         <!--ACTION: Remove (Confirms twice)-->
<?php
     enddiv();
     hprint(2, "spellsaves", "Spell Save DC");
     newdiv("spellsaves");
     #pstdaction();
?>
      <!--ACTION: Update-->
      <!--LOOPGEN: Per-level-->
       <!--TRACKED: per-level: Save DC, Spells per Day, Bonus Spells-->
<?php
   enddiv();
   enddiv();
   enddiv();
?>
  </form>
 </body>
</html>
